package com.baichuan.zntx.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baichuan.common.core.utils.DateUtils;
import com.baichuan.common.core.utils.MapstructUtils;
import com.baichuan.common.core.utils.StringUtils;
import com.baichuan.common.mybatis.core.page.TableDataInfo;
import com.baichuan.common.mybatis.core.page.PageQuery;
import com.baichuan.common.satoken.utils.LoginHelper;
import com.baichuan.common.websocket.utils.WebSocketUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.baichuan.zntx.domain.bo.MessageBo;
import com.baichuan.zntx.domain.vo.MessageVo;
import com.baichuan.zntx.domain.Message;
import com.baichuan.zntx.mapper.MessageMapper;
import com.baichuan.zntx.service.IMessageService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 报警消息管理Service业务层处理
 *
 * @author Baichuan
 * @date 2024-05-11
 */
@EnableScheduling
@RequiredArgsConstructor
@Service
public class MessageServiceImpl implements IMessageService {

    private final MessageMapper baseMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    private void queryUnreadMsg(){
        List<Message> messages = baseMapper.selectList(new LambdaQueryWrapper<Message>()
            .lt(Message::getStatus, 1));
        messages.forEach(msg -> {
            WebSocketUtils.sendMessage2All(JSONUtil.toJsonStr(msg));
            msg.setSendTime(DateUtils.getNowDate());
            msg.setSendCount(msg.getSendCount() + 1);
            msg.setStatus(0);
        });
        if(!messages.isEmpty())
            baseMapper.updateBatchById(messages);
    }
    /**
     * 查询报警消息管理
     */
    @Override
    public MessageVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询报警消息管理列表
     */
    @Override
    public TableDataInfo<MessageVo> queryPageList(MessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Message> lqw = buildQueryWrapper(bo);
        Page<MessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询报警消息管理列表
     */
    @Override
    public List<MessageVo> queryList(MessageBo bo) {
        LambdaQueryWrapper<Message> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Message> buildQueryWrapper(MessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceId()), Message::getDeviceId, bo.getDeviceId());
        lqw.eq(bo.getType() != null, Message::getType, bo.getType());
        lqw.eq(bo.getStatus() != null, Message::getStatus, bo.getStatus());
        lqw.orderByDesc(Message::getCreateTime).orderByAsc(Message::getStatus);
        return lqw;
    }

    /**
     * 新增报警消息管理
     */
    @Override
    public Boolean insertByBo(MessageBo bo) {
        Message add = MapstructUtils.convert(bo, Message.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改报警消息管理
     */
    @Override
    public Boolean updateByBo(MessageBo bo) {
        Message update = MapstructUtils.convert(bo, Message.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Message entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除报警消息管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean readMessage(String id) {
        Message message = baseMapper.selectById(id);
        if(message == null){
            return false;
        }
        message.setStatus(1);
        return baseMapper.updateById(message) > 0;
    }
}
